package xdu.lz.stage1_basic.chapter5_threadPool;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class SimpleThreadPool2 {
    //线程数
    private final int size;
    //默认大小
    private static final int DEFAULT_SIZE = 10;
    //线程任务队列
    private final static Queue<Runnable> TASK_QUEUE = new LinkedList<>();
    //默认支持的任务数量
    private static final int DEFAULT_TASK_QUEUE_SIZE = 2000;
    private final int queueSize;
    //管理线程池中激活的线程【指的是启动的线程池中的线程，不是提交的任务】
    private final static List<WorkerTask> THREAD_POOL_LIST = new ArrayList<>();
    //线程组
    private static final ThreadGroup GROUP = new ThreadGroup("POOL_GROUP");
    private static final String THREAD_PREFIX = "SIMPLE_THREAD_POOL";
    //线程编号
    private static volatile int seq = 0;
    //线程池是否被关闭
    private volatile boolean discard = false;
    //拒绝策略
    private final DiscardPolicy discardPolicy;
    //拒绝策略接口
    @FunctionalInterface
    public interface DiscardPolicy{
        void discard() throws DiscardException;
    }
    public static class DiscardException extends RuntimeException{
        public DiscardException(String msg){
            super(msg);
        }
    }
    //拒绝策略的默认实现方式:直接抛异常
    public static final DiscardPolicy DEFAULT_DISCARD_POLICY = ()->{
      throw new DiscardException("任务队列已满！");
    };
    public SimpleThreadPool2(){
        this(DEFAULT_SIZE,DEFAULT_TASK_QUEUE_SIZE,DEFAULT_DISCARD_POLICY);
    }

    public SimpleThreadPool2(int size,int queueSize,DiscardPolicy discardPolicy) {
        this.size = size;
        this.queueSize = queueSize;
        this.discardPolicy = discardPolicy;
        init();
    }

    //创建线程
    private void init() {
        for (int i = 0; i < size; i++) {
            createWorkTask();
        }
    }
    //提交任务
    public void submit(Runnable task){
        if(this.discard){
            throw new IllegalStateException("线程池已经被关闭");
        }
        synchronized (TASK_QUEUE){
            //执行拒绝策略
            if (TASK_QUEUE.size() > queueSize){
                discardPolicy.discard();
            }
            TASK_QUEUE.offer(task);
            //提交任务后通知
            TASK_QUEUE.notifyAll();
        }
    }

    //创建线程
    private void createWorkTask(){
        WorkerTask task = new WorkerTask(GROUP,THREAD_PREFIX +(seq++));
        //开启线程
        task.start();
        //任务已经被执行
        THREAD_POOL_LIST.add(task);
    }

    //线程状态
    private enum TaskState{
        FREE,RUNNING,BLOCK,DEAD
    }
    private static class WorkerTask extends Thread{
        private volatile TaskState taskState = TaskState.FREE;
        public WorkerTask(ThreadGroup group,String name){
            super(group,name);
        }

        @Override
        public void run() {
            Outer:
            while (this.taskState != TaskState.DEAD){
                System.out.println("2");
                Runnable runnable;
                synchronized (TASK_QUEUE){
                    while (TASK_QUEUE.isEmpty()){
                        taskState = TaskState.BLOCK;
                        try {
                            //如果任务队列是空则等待，当有任务加入任务队列，会被唤醒
                            TASK_QUEUE.wait();
                        } catch (InterruptedException e) {
                            break Outer;
                        }
                    }
                    runnable = TASK_QUEUE.poll();
                }
                if(runnable != null){
                    taskState = TaskState.RUNNING;
                    runnable.run();
                    taskState = TaskState.FREE;
                }
            }
        }

        public TaskState getTaskState() {
            return taskState;
        }
        public void close(){
            this.taskState = TaskState.DEAD;
        }

    }

    public void shutdown() throws InterruptedException {
        //如果任务队列还有任务，则先让他把任务都提交完
        System.out.println("***********************************************");
        while (!TASK_QUEUE.isEmpty()) {
            Thread.sleep(50);
        }
        System.out.println(1111);
        //关闭所有已经创建的线程
        int initVal = THREAD_POOL_LIST.size();
        while (initVal > 0) {
            for (WorkerTask workerTask : THREAD_POOL_LIST) {
                //如果是阻塞，则代表任务队列是空，
                // 等待任务队列来任务，可以直接关闭该线程了
                if (workerTask.getTaskState() == TaskState.BLOCK) {
                    workerTask.close();//把状态置位dead
                    workerTask.interrupt();
                    initVal--;
                } else {
                    //否则代表还有任务在执行，等一小会
                    Thread.sleep(10);
                }
            }
        }
        //线程池已经被关闭置位true
        this.discard = true;
        System.out.println("线程池被关闭了..");
    }

    public static void main(String[] args) throws InterruptedException {
        SimpleThreadPool2 threadPool = new SimpleThreadPool2(5,30,
                SimpleThreadPool2.DEFAULT_DISCARD_POLICY);
        for (int i = 0; i < 4000; i++) {
            int finalI = i;
            try{
                threadPool.submit(()->{
                    System.out.println(finalI + "the runnable be serviced by "+Thread.currentThread()+" " +
                            "start.");
                    try {
                        Thread.sleep(20);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(finalI +"the runnable be serviced by "+Thread.currentThread()+" end.");
                });
            }catch (Exception e){
                System.out.println(e.getMessage());
            }

            System.out.println("i = " + i);
        }
        //等待任务执行
        Thread.sleep(1000);
        threadPool.shutdown();
        threadPool.submit(()->{});
    }
}
